<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/18
 * Time: 10:21
 */

namespace app\mall\controller;


use app\admin\model\GoodsCategory;
use app\admin\model\GoodsList;

class Goods extends Base
{

    /**
     * 商品分类列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function categoryList(){
        $data = GoodsCategory::where('status',1)->order('sort desc')->select()->toArray();
        if (!$data){
            return json(['code'=>0,'msg'=>'无数据']);
        }
        $ones = [];
        foreach ($data as $k=>$v){
            $ones[$v['id']] = $v;
        }
        $tree = [];
        foreach ($ones as $item){
            if (isset($ones[$item['pid']])){
                $ones[$item['pid']]['sub'][] = &$ones[$item['id']];
            }else{
                $tree[] = &$ones[$item['id']];
            }
        }
        return json(['code'=>1,'msg'=>'返回成功','data'=>$tree]);
    }

    /**
     * 商品列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList(){
        $page = (int)input('post.page');
        $limit = (int)input('post.limit');
        if ($page == 0){
            return json(['code'=>-1,'msg'=>'参数page不能为空']);
        }
        if ($limit == 0){
            return json(['code'=>-1,'msg'=>'参数limit不能为空']);
        }
        $category = input('post.category_id')?['category_id'=>(int)input('post.category_id')]:'';
        $where = input('post.where')?[['good_name','like','%'.input('post.where').'%']]:'';
        $data = GoodsList::where('status',1)
            ->where($where)
            ->where($category)
            ->order('create_time desc')
            ->field('id,good_name,image,price,sell')
            ->page($page,$limit)
            ->select()->each(function ($item){
                $item->image = $this->url.$item->image;
            })->toArray();
        if (!$data){
            return json(['code'=>0,'msg'=>'无数据']);
        }
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
    }

}